/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.controller.glc;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.dao.bt.baseinfo.BaseInfoDao;
import com.plian.system.dto.pf.BaseBusinessAnnualDTO;
import com.plian.system.entity.hr.dept.Dept;
import com.plian.system.entity.jlr.JlrStaffManagement;
import com.plian.system.entity.pf.BaseBusinessAnnual;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.glcydgz.IGlcBaseBusinessAnnualService;
import com.plian.system.service.hr.dept.IDeptService;
import com.plian.system.service.jlr.IJlrStaffManagementService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pf.BaseBusinessAnnualVO;
import com.plian.system.vo.pf.BaseBusinessIndicatorsVO;
import com.plian.system.wrapper.pf.BaseBusinessAnnualWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

/**
 * 经营业绩考核年度调整 控制器
 *
 * @author
 * @since 2019-09-27
 */
@RestController
@AllArgsConstructor
@RequestMapping("api/glcBasebusinessannual")
@Api(value = "BaseBusinessAnnualController", tags = "管理层经营业绩考核年度调整 控制器")
public class GlcBaseBusinessAnnualController extends BaseController {

	private FormWorkflowService formWorkflowService;

	private IGlcBaseBusinessAnnualService glcBaseBusinessAnnualService;

	private BaseBusinessAnnualWrapper baseBusinessAnnualWrapper;

	private GzwProperties gzwProperties;
	private IJlrStaffManagementService jlrStaffManagementService;
	private IDeptService deptService;
	@Autowired
	BaseInfoDao baseInfoDao;
	@PostMapping("/detail")
	@ApiOperation(value = "详情", notes = "传入 baseBusinessAnnual")
	public R<BaseBusinessAnnualVO> detail(@RequestBody BaseBusinessAnnual baseBusinessAnnual) {
		baseBusinessAnnual.setModuleType(1);
		BaseBusinessAnnual detail = glcBaseBusinessAnnualService.getOne(Condition.getQueryWrapper(baseBusinessAnnual));
		BaseBusinessAnnualVO baseBusinessAnnualVO = baseBusinessAnnualWrapper.entityToVO(detail);
		getVoDetail(baseBusinessAnnualVO);
		return glcBaseBusinessAnnualService.getDetailObj(baseBusinessAnnualVO);
	}
	/**
	 * 在vo响应中添加经理层档案中的信息
	 * @param vo
	 */
	public void getVoDetail(BaseBusinessAnnualVO vo){
		if(vo!=null&&vo.getStaffId()!=null){
			JlrStaffManagement staffFiles=new JlrStaffManagement();
			staffFiles.setId(Long.parseLong(vo.getStaffId()));
			JlrStaffManagement one =jlrStaffManagementService.getOne(Condition.getQueryWrapper(staffFiles));
			if(one!=null){
				if(one.getDepartmentNameId()!=null){
					Dept dept=new Dept();
					dept.setId(Long.parseLong(one.getDepartmentNameId()));
					Dept deptDetail = deptService.getOne(Condition.getQueryWrapper(dept));
					vo.setDepartmentNameId(one.getDepartmentNameId());
					if(deptDetail!=null&&deptDetail.getDeptName()!=null&&!deptDetail.getDeptName().equals("")){
						vo.setDepartmentName(deptDetail.getDeptName());
					}
				}
				if(StringUtil.isNotBlank(one.getManagementCategoryId())){
					vo.setManagementCategoryId(one.getManagementCategoryId());
					try{
						PageData p=baseInfoDao.findbycode(one.getManagementCategoryId());
						if(p!=null){
							String name=p.getString("name");
							if(StringUtil.isNotBlank(name)){
								vo.setManagementCategoryName(name);
							}
						}
					} catch (Exception e){
						e.getStackTrace();
					}
				}
				if(StringUtil.isNotBlank(one.getJobNameId())){
					vo.setJobNameId(one.getJobNameId());
				}
				if(StringUtil.isNotBlank(one.getStaffName())){
					vo.setStaffName(one.getStaffName());
				}

			}
		}
	}
	@PostMapping("/list")
	@ApiOperation(value = "分页", notes = "传入query")
	public ListResult<BaseBusinessAnnualVO> list(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
		if (query.getAscs()==null&&query.getDescs()==null){
			query.setDescs("create_time");
		}
		QueryWrapper<BaseBusinessAnnual> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new BaseBusinessAnnual()), entityList
		);
		queryWrapper.eq("module_type",1);
		String tokenOrgId = TokenUtil.getTokenOrgId();
		boolean flag = false;
		if (CollectionUtil.isEmpty(entityList)){
			flag = true;
		}else {
			for (SearchEntity entity:entityList){
				if ("filling_unit_id".equals(entity.getField())){
					flag = true;
				}
			}
		}
		if (flag && !(tokenOrgId.equals(gzwProperties.getId()) || tokenOrgId.equals(gzwProperties.getReportId()))){
			queryWrapper.eq("filling_unit_id",tokenOrgId);
		}
		IPage<BaseBusinessAnnual> pages = glcBaseBusinessAnnualService.page(Condition.getPage(query), queryWrapper);
		List<BaseBusinessAnnualVO> baseBusinessAnnualVOS = baseBusinessAnnualWrapper.entityToVO(pages.getRecords());
		for (BaseBusinessAnnualVO baseBusinessAnnualVO: baseBusinessAnnualVOS) {
			getVoDetail(baseBusinessAnnualVO);
		}
		ListResult<BaseBusinessAnnualVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(baseBusinessAnnualVOS);
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
		return listResult;
	}

	@PostMapping("/submit")
	@Resubmit(delaySeconds = 0)
	@LogOperation("经营业绩考核年度调整-提交")
	@ApiOperation(value = "新增或修改", notes = "传入 baseBusinessAnnual")
	public R<BaseBusinessAnnual> submit(@Valid @RequestBody BaseBusinessAnnual baseBusinessAnnual) {
		baseBusinessAnnual.setModuleType(1);
		String checkMessage = glcBaseBusinessAnnualService.checkYear(baseBusinessAnnual);
		if (StringUtil.isNotBlank(checkMessage)){
			return new R(CustomCode.builder().message(checkMessage).code(1999).success(false).build());
		}

		boolean result = glcBaseBusinessAnnualService.submit(baseBusinessAnnual);
		HashMap<String, Object> processVariable = new HashMap<>();
		formWorkflowService.startProcessAndSimulate(String.valueOf(baseBusinessAnnual.getId()),baseBusinessAnnual.getFormType(),processVariable);

		return result ? R.data(baseBusinessAnnual) : new R(CommonCode.FAIL);
	}

	@PostMapping("/remove")
	@LogOperation("经营业绩考核年度调整-删除")
	@ApiOperation(value = "删除", notes = "传入 ids")
	public R remove(@RequestBody PageData pd) {
		List<String> ids = (List<String>)pd.get("ids");
		return glcBaseBusinessAnnualService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
				? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
	}

	@PostMapping("/getDetailByDto")
	@ApiOperation(value = "根据年度和填报时间获取基础表", notes = "传入 dto")
	public R<BaseBusinessAnnualVO> getDetailByDto(@RequestBody BaseBusinessAnnualDTO dto) {
		dto.setModuleType(1);
		BaseBusinessAnnual baseBusinessAnnual = new BaseBusinessAnnual();
		baseBusinessAnnual.setFillingUnitId(dto.getFillingUnitId());
		baseBusinessAnnual.setFillingYear(dto.getFillingYear());
		baseBusinessAnnual.setModuleType(1);
		String checkMessage = glcBaseBusinessAnnualService.checkYear(baseBusinessAnnual);
		if (StringUtil.isNotBlank(checkMessage)){
			return new R(CustomCode.builder().message(checkMessage).code(1999).success(false).build());
		}
		BaseBusinessAnnualVO detailByDto = glcBaseBusinessAnnualService.getDetailByDto(dto);
		return R.data(detailByDto);
	}

}
